"""死锁"""
from threading import Thread, Lock
from time import sleep


# 交易类
class Account:
    def __init__(self, name, balance, lock):
        self.name = name
        self.__balance = balance
        self.lock = lock

    def withdraw(self, amount):
        self.__balance -= amount

    def transfer(self, amount):
        self.__balance += amount

    @property
    def get_balance(self):
        return self.__balance


Tom = Account('Tom', 5000, Lock())
Bob = Account('Bob', 8000, Lock())
# 转账过程
def transfer(from_account, to_account,amount):
    if from_account.lock.acquire():# 锁住自己的账户
        from_account.withdraw(amount)
        sleep(1)
        if to_account.lock.acquire(): # 对方账户上锁
            to_account.transfer(amount)
            to_account.lock.release()
        from_account.lock.release()
        print("%s给%s转账%d"%(from_account.name, to_account.name,amount))

t1=Thread(target=transfer,args=(Tom,Bob,100))
t2=Thread(target=transfer,args=(Bob,Tom,200))
t1.start()
t2.start()
t1.join()
t2.join()
